package com.linkage.bookshop.authentication;


import java.io.IOException;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.linkage.bookshop.model.Role;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	@Resource
	private UserDetailsService myUserCredentialProvider;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		UserCredential userCredential =	(UserCredential) myUserCredentialProvider.loadUserByUsername(username);
		Set<Role> roles = userCredential.getUser().getRoles();
		
		for(Role role:roles){
			if(role.getName().equals("MEM_COMMON")){
				response.sendRedirect(request.getContextPath()+ "/");
				return;
			}
		}
		
		for(Role role:roles){
			if(role.getName().matches("^ADM_.*")){
				response.sendRedirect(request.getContextPath()+ "/adminHome");
				return;
			}
		}
	}

}
